<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/23 0023
 * Time: 15:59
 */

namespace app\api\controller;

use think\Controller;
use think\cache\driver\Redis;
use think\Exception;

/**
 *  自定义菜单执行文件
 * Class ConsoleMenuCustom
 * @package app\api\controller
 */
class ConsoleMenuCustom extends Controller
{
    const API_MENU_CREATE = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=';
    const APPLET_APP_ID = 'wx949e0f0219401710'; // 要跳转的小程序app_id
    const APPLET_ORIGINAL_ID ='gh_3b5e14df2085';// 自定义菜单所在公众号的原始ID

    /**
     * 创建自定义菜单
     * @return \think\response\Json
     */
    public function create() {
        $request_data = $this->toJson($this->getRequestData());
        $request_url = self::API_MENU_CREATE . $this->getAccessToken(self::APPLET_ORIGINAL_ID);
        try{
            $result = $this->https_request($request_url, $request_data);
            $result = json_decode($result, true);
            if ($result['errcode'] != 0) {
                throw new Exception($result['errmsg']);
            }
            return json(['code' => 1, 'msg' => 'success']);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 自定义菜单的数据
     *
     * @return array
     */
    private function getRequestData() {
        return [
            'button' => [
                [
                    'name' => '继续集卡',
                    'sub_button' => [
                        [
                            'type' => 'miniprogram',
                            'name' => '王者集卡礼包',
                            'url' => 'http://mw.daxuedaohang.com/index.php?g=Wap&m=Tietie1&a=index&token=cadrqk1465898733&do=new',
                            'appid' => self::APPLET_APP_ID,
                            'pagepath' => 'pages/index?gzh=true'
                        ]
                    ]
                ],
                [
                    'name' => '免费领取',
                    'sub_button' => [
                        [
                            'type' => 'view',
                            'name' => '玩体验服',
                            'url' => 'http://pvp.qq.com/cp/a20161115tyf/page1.shtml',
                        ],
                        [
                            'type' => 'view',
                            'name' => '战绩查询',
                            'url' => 'https://game.weixin.qq.com/cgi-bin/h5/static/pc_detail/index.html?appid=wx95a3a4d7c627e07d&ssid=1&abt=#wechat_redirect',
                        ],
                    ],
                ],
                [
                    'type' => 'view',
                    'name' => '大神直播',
                    'url' => 'http://www.owzhushou.com/live.php'
                ],
            ],
        ];
    }

    /**
     * 获取access_token
     * @param $original_id
     * @return
     */
    private function getAccessToken($original_id) {
        $token_redis_key = "WX_CONFIG:OriginalId:".$original_id;
        $redis = new Redis();
        $wx_config = $redis->get($token_redis_key);
        return $wx_config['access_token'];
    }

    /**
     * 发送http请求
     * @param $url
     * @param null $data
     * @return mixed
     */
    private function https_request($url, $data = null) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 对数据进行转码，避免中文转json时乱码
     * @param array & string $data
     */
    public function toJson($data) {
        $data = json_encode($this->urlencodeAry($data));
        return urldecode($data);
    }

    /**
     * 将数据进行urlencode
     * @param array & string $data
     */
    public function urlencodeAry($data) {
        if(is_array($data)) {
            foreach($data as $key=>$val) {
                $data[$key] = $this->urlencodeAry($val);
            }
            return $data;
        } else {
            return urlencode($data);
        }
    }
}